<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use JWTAuth;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Tymon\JWTAuth\Exceptions\JWTException;
use Exception;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
//         $this->middleware('guest')->except('logout');
    }

    /**
     * 处理用户登录逻辑
     *
     * Date: 2018/1/25
     * @author yl
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function api_login(Request $request)
    {
        $credentials = $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    // 'status' => 'error',
                    'error' => '认证失败，用户名或密码不正确'
                ], 401);
            }
        } catch (JWTException $exception) {
            return response()->json([
                // 'status' => 'error',
                'error' => '未知错误，请稍后再试'
            ], 500);
        }

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => config('jwt.ttl') * 60
        ]);
    }

    /**
     * 注销用户
     *
     * Date: 2018/1/25
     * @author yl
     * @return \Illuminate\Http\JsonResponse
     */
    public function api_logout()
    {
        try {
            $this->guard()->logout();
        } catch (Exception $exception) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Error'
            ], 500);
        }
        return response()->json([
            'status' => 'success',
            'message' => '注销成功'
        ]);
    }

    public function username()
    {
        return 'account_id';
    }
}
